import { getMyCourses } from '../../api/myCourse';

Page({
  data: {
    currentTab: 'watch',
    watchRecords: [],
    collectRecords: [],
    myCourses: [],
    courseIdList: [],
    loading: false,
    errorMsg: ''
  },
  
  onLoad: function () {
    
  },

  onShow: function(){
    this.getMyCourseData();
    console.log(this.data.collectRecords);
  },
  
  switchTab: function (e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ currentTab: tab });
  },
  
  getMyCourseData: function () {
    this.setData({ loading: true, errorMsg: '' });
    
    getMyCourses()
    .then(data => {
      console.log('collectList 原始数据:', data.collectList || []);
      const collectList = [];
      const filteredWatchData = this.filterWatchFields(data.recordList || []);
      const filteredCollectData = this.filterCollectFields(data.collectList || []);
      for(var i = 0; i <  data.collectList.length; i++) {
        collectList.push(data.collectList[i].courseId)
      }
      this.setData({
        myCourses: data,
        watchRecords: filteredWatchData,
        collectRecords: filteredCollectData,
        loading: false
      });
    })
    .catch(err => {
      console.error('获取课程数据失败:', err);
      this.setData({
        loading: false,
        errorMsg: '获取课程数据失败，请稍后重试'
      });
    });
    
  },
  
  // 筛选观看记录字段
  filterWatchFields: function (originalData) {
    const courseList = Array.isArray(originalData) ? originalData : [originalData];
    return courseList.map(course => ({
      courseId: course.courseId,
      courseTitle: course.courseTitle,
      courseSubtitle: course.courseSubtitle || '无副标题',
      coverFileUrl: course.coverFileUrl || '',
      courseLevel: this.getCourseLevelText(course.courseLevel),
      progress: course.progress || 0
    }));
  },
  
  // 筛选收藏课程字段
  filterCollectFields: function (originalData) {
    const courseList = Array.isArray(originalData) ? originalData : [originalData];
    return courseList.map(course => ({
      courseId: course.courseId,
      courseTitle: course.courseTitle,
      courseSubtitle: course.courseSubtitle || '无副标题',
      coverFileUrl: course.coverFileUrl || '',
      courseBanner: course.courseBanner || '',
      bannerFileUrl: course.bannerFileUrl || '',
      courseLevel: this.getCourseLevelText(course.courseLevel),
      courseDetail: course.courseDetail || '暂无课程详情',
      coursePrice: course.coursePrice || 0,
      discountPrice: course.discountPrice || 0,
      discountDesc: course.discountDesc || ''
    }));
  },
  
  // 转换课程难度文本
  getCourseLevelText: function (level) {
    const levelMap = { '1': '初级', '2': '中级', '3': '高级' };
    return levelMap[level] || '未知难度';
  },
  
  // 观看记录跳转introduct页（静态+动态）
  gotoDetail(e) {
    // 1. 获取课程ID
    const courseId = e.currentTarget.dataset.courseid;
    if (!courseId) {
      wx.showToast({ title: '课程ID异常', icon: 'none', duration: 1500 });
      return;
    }
    
    // 2. 跳转到introduct页
    wx.navigateTo({
      url: `/pages/introduct/introduct?courseId=${courseId}`,
      success: () => console.log('跳转introduct页成功，courseId：', courseId),
      fail: (err) => {
        console.error('跳转失败：', err);
        wx.showToast({ title: '跳转失败，请重试', icon: 'none' });
      }
    });
  },
  
  // 收藏记录跳转introduct页
  onCollectCourseTap: function (e) {
    const courseId = e.currentTarget.dataset.courseid;
    if (!courseId) {
      wx.showToast({ title: '课程ID异常', icon: 'none', duration: 1500 });
      return;
    }
    
    // 跳转到introduct页
    wx.navigateTo({
      url: `/pages/introduct/introduct?courseId=${courseId}`,
      success: () => console.log('收藏课程跳转introduct页成功，courseId：', courseId),
      fail: (err) => {
        console.error('跳转失败：', err);
        wx.showToast({ title: '跳转失败，请重试', icon: 'none' });
      }
    });
  },
  
  reloadData: function () {
    this.getMyCourseData();
  }
});
